import os
from django.shortcuts import render,HttpResponse
from django import forms
from django.template.defaultfilters import title

from app01.utils.bootstrap import BootStrapForm,BootStrapModelForm
from app01 import models
from django.conf import settings


def upload_list(request):
    """上传文件"""
    if request.method == "GET":
        return render(request,'upload_list.html')
    # 获取文件对象
    file_object = request.FILES.get("avatar")
    print(file_object.name)

    # 把读取到的文件写入XX
    f = open('a1.png', mode='wb')
    # 读取对象文件内容
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()

    return HttpResponse("...")

class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']

    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")

def upload_form(request):
    """Form上传方法"""
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request,"upload_form.html",{"form": form,"title":title})

    form = UpForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # print(form.cleaned_data)
        # {'name': '测试', 'age': 18, 'img': <InMemoryUploadedFile: 屏幕截图 2024-12-18 211135.png (image/png)>}
        # 1,读取图片内容，写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get('img')
        # 图片存储到数据库中，如果要展示给用户看就把这个地址拼接URL给用户，因为"app01"地址用户看不到
        # 启用media文件，配置路径，settings.MEDIA_ROOT，绝对路径
        # media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        # 相对路径
        media_path = os.path.join("media", image_object.name)
        # 保证格式稳定用OS路径
        # file_path = os.path.join("app01", db_file_path)
        f = open(media_path,mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()

        # 2,将图片文件路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data["name"],
            age=form.cleaned_data["age"],
            img=media_path,
        )

        return HttpResponse("上传成功")
    return render(request,"upload_form.html",{"form":form,"title":title})

class UpModelForm(BootStrapModelForm):
    # 定义ModelForm
    bootstrap_exclude_fields = ['img']
    class Meta:
        model = models.City
        fields = "__all__"


def upload_modal_form(request):
    """上传文件和数据modelForm"""
    title = "ModelForm上传文件"
    if request.method == "GET":
        form = UpModelForm()
        return render(request,"upload_form.html",{"form":form,"title":title})
    form = UpModelForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # 对于文件：ModelForm自动保存；
        # 字段 + 上传路径写入到数据库
        form.save()
        return HttpResponse("OK")
    return render(request,"upload_form.html",{"form":form,"title":title})